#ifndef _M_FMT_H_
#define _M_FMT_H_

#include "level.hpp"
#include "logmsg.hpp"
#include <ctime>
#include <vector>
#include <cassert>
#include <sstream>

namespace HUE
{
    // 抽象格式化子项基类
    class FromatIem
    {
    public:
        using ptr = std::shared_ptr<FromatIem>;
        virtual void format(std::ostream &out,const LogMsg &msg) = 0;
    };

    // 派生格式化子项子类 -- 消息 等级 时间 文件名 行号 线程ID 日志器名 制表符 换行 其他

    class LevelFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };

    class TimeFormatItem : public FromatIem
    {
    public:
        TimeFormatItem(const std::string &fmt = "%H:%M:%S") : _time_fmt(fmt) {}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char tmp[32] = {0};
            strftime(tmp, 31, _time_fmt.c_str(), &t);

            out << tmp;
        }

    private:
        std::string _time_fmt; // 格式 %H：%M：％S
    };

    class FileFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    class LineFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    class ThreadFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._tid;
        }
    };

    class LoggerFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._logger;
        }
    };

    class MsgFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class TabFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << "\t";
        }
    };

    class NLineFormatItem : public FromatIem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };

    // 其他字符：
    class OtherFormatItem : public FromatIem
    {
    public:
        OtherFormatItem(const std::string &str) : _str(str) {}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    /*
         %d 时间
         %t 线程ID
         %c 日志器名称
         %f 源码文件名
         %l 源码行号
         %p 日志级别
         %T 制表符缩进
         %m 主体消息
         %n 换行符
    */

    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }

        // 对msg进行格式化
        void format(std::ostream &out, const LogMsg &msg)
        {
            for (auto &item : _items)
            {
                item->format(out, msg); // 按照顺序把信息从msg取出来
            }
        }
        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }

        private:
        // 对格式化规则字符串进行解析
        bool parsePattern()
        {
           //1.对格式化规则字符串进行解析
            //ab%%cd[%d{%H:%M:%S}][%p][%f:%l]%T%m%n

            std::vector<std::pair<std::string,std::string>>fmt_order;
            size_t pos =0;

            std::string key,val;
            while (pos <_pattern.size())
            {
                //1. 判断处理原始字符串，是否为%,否为原始字符
                if(_pattern[pos] !='%')
                {
                    val.push_back(_pattern[pos++]); continue;
                }
                //能走下来代表pos位置为%,%%处理称为一个原始%字符
                if(_pattern[pos+1] =='%' && pos+1 < _pattern.size())
                {
                    val.push_back('%'); pos+=2; continue;
                }
                //能走下来代表%后面是个格式化字符,代表原始字符串处理完毕
                if(val.empty() == false){
                fmt_order.push_back(std::make_pair("",val));
                val.clear();
                }

                //格式化字符处理 
                pos+=1; //这一步之后，pos指向格式化字符位置
                if(pos == _pattern.size())
                {
                    std::cout << "%之后，没有对应的格式化字符！\n";
                    return false;
                }
                key = _pattern[pos];
                //+1此时pos指向格式化字符后的位置
                pos+=1;
                if(pos<_pattern.size() && _pattern[pos] =='{')
                {
                    pos+=1;//此时pos指向子规则的起始位置
                    while(pos<_pattern.size() && _pattern[pos] !='}')
                    {
                        val.push_back(_pattern[pos++]);
                    }
                    //如果是走到了末尾跳出循环，则代表没有遇到 },格式错误
                    if(pos == _pattern.size())
                    {
                        std::cout << "子规则{}匹配出错！\n";
                        return false;
                    }
                    pos +=1; //因为此时pos指向的 }位置，需要向后走一步，更新位置
                }   
                
                fmt_order.push_back(std::make_pair(key,val));
                key.clear();
                val.clear();
            }
            
            //2.根据解析得到的数据初始化格式化子项数组成员

            for(auto &it:fmt_order)
            {
                _items.push_back(createItem(it.first,it.second));
            }
            return true;
        }

        // 跟进不同的格式化字符创建不同的格式化子项对象
        FromatIem::ptr createItem(const std::string &key, const std::string &val)
        {
        if(key == "d") return std::make_shared<TimeFormatItem>(val);
        if(key == "t") return std::make_shared<ThreadFormatItem>();
        if(key == "c") return std::make_shared<LoggerFormatItem>();
        if(key == "f") return std::make_shared<FileFormatItem>();
        if(key == "l") return std::make_shared<LineFormatItem>();
        if(key == "p") return std::make_shared<LevelFormatItem>();
        if(key == "T") return std::make_shared<TabFormatItem>();
        if(key == "m") return std::make_shared<MsgFormatItem>();
        if(key == "n") return std::make_shared<NLineFormatItem>();
        if(key == "")  return std::make_shared<OtherFormatItem> (val);
        std::cout << "没有对应的格式化字符：%"<<key<<std::endl;
        abort();
        }

    private:
        std::string _pattern; // 格式化规则字符串
        std::vector<FromatIem::ptr> _items;
    };

}

#endif
